﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Polaris.Common.DomainInterfaces;
using Polaris.Domain.Model.Entity.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Polaris.EntityFrameworkCore
{
    public class EFRepository : IRepository
    {
        private readonly DbContext _dbContext;

        /// <summary>
        /// 事务
        /// </summary>
        private IDbContextTransaction? _transaction;

        /// <summary>
        /// 是否提交
        /// </summary>
        private bool _isCommit = false;


        public EFRepository(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 提交
        /// </summary>
        public void Commit()
        {
            try
            {
                _dbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.FAIL, ex.Message);
            }

        }
        /// <summary>
        /// 异步提交
        /// </summary>
        /// <returns></returns>
        public async Task CommitAsync()
        {
            try
            {
                await _dbContext.SaveChangesAsync(CancellationToken.None);
            }
            catch (Exception ex)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.FAIL, ex.Message);
            }
        }

        /// <summary>
        /// 内存回收
        /// </summary>
        public void Dispose()
        {
            _dbContext.Dispose();
            GC.Collect();
        }

        #region 事务

        /// <summary>
        /// 开启事务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void BeginTransaction()
        {
            _transaction = _dbContext.Database.BeginTransaction();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void CommitTransaction()
        {
            if (_transaction != null)
            {
                _transaction.Commit();
            }
            _isCommit = true;
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void Rollback()
        {
            // 未提交事务，回滚
            if (_transaction != null && !_isCommit)
            {
                _transaction.Rollback();
            }
            // 提交过的事务，释放资源
            if (_transaction != null)
            {
                _transaction.Dispose();
            }
        }

        #endregion
    }
}
